package com.ytktt.study.week12.task11.config;

import com.ytktt.study.week12.task11.properties.MqttProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * MQTT出站配置
 *
 * @author ytk
 */
@Slf4j
@RequiredArgsConstructor
@Configuration
public class MqttOutboundConfiguration {

    private final MqttPahoClientFactory mqttClientFactory;
    private final MqttProperties mqttProperties;

    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(this.mqttProperties.getClientId(), this.mqttClientFactory);
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(this.mqttProperties.getTopic());
        messageHandler.setDefaultQos(this.mqttProperties.getQos());
        return messageHandler;
    }

    @Bean(name = "mqttOutboundChannel")
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

}
